package threadjuc;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * @author zxl
 * @version 1.0
 * @date 2021/10/28 9:46
 * ArrayBlockingQueue 阻塞队列
 * 四种API
 */
public class Juc13 {
    public static void main(String[] args) throws InterruptedException {
        test4();
    }

    /**
     * 1,抛出异常
     */
    private static void test1() {
        ArrayBlockingQueue<Object> objects = new ArrayBlockingQueue<>(3);
        objects.add("a");
        objects.add("b");
        objects.add("c");
//        objects.add("d");  //Queue full 抛出异常

        //查看队首元素
        System.out.println(objects.element());

        System.out.println(objects.remove());
        System.out.println(objects.remove());
        System.out.println(objects.remove());
//        System.out.println(objects.remove());   //NoSuchElementException  异常

    }

    /**
     * 2,不抛出异常，有返回值
     */
    private static void test2() {
        ArrayBlockingQueue<Object> objects = new ArrayBlockingQueue<>(3);
        objects.offer("a");
        objects.offer("b");
        objects.offer("c");
//        objects.offer("d");  //不抛出异常

        //查看队首元素
        System.out.println(objects.peek());

        System.out.println(objects.poll());
        System.out.println(objects.poll());
        System.out.println(objects.poll());
//        System.out.println(objects.poll());   //不抛出异常

    }

    /**
     * 3,不抛出异常，阻塞等待
     */
    private static void test3() throws InterruptedException {
        ArrayBlockingQueue<Object> objects = new ArrayBlockingQueue<>(3);
        objects.put("a");
        objects.put("b");
        objects.put("c");
//        objects.put("d");  //不抛出异常  阻塞

        //查看队首元素
        System.out.println(objects.peek());

        System.out.println(objects.take());
        System.out.println(objects.take());
        System.out.println(objects.take());
//        System.out.println(objects.take());   //不抛出异常 阻塞

    }

    /**
     * 4,不抛出异常，超时等待
     */
    private static void test4() throws InterruptedException {
        ArrayBlockingQueue<Object> objects = new ArrayBlockingQueue<>(3);
        objects.offer("a", 2, TimeUnit.SECONDS);
        objects.offer("b", 2, TimeUnit.SECONDS);
        objects.offer("c", 2, TimeUnit.SECONDS);
//        objects.offer("d",2, TimeUnit.SECONDS);  //不抛出异常，等待两秒后结束

        System.out.println(objects.poll(2, TimeUnit.SECONDS));
        System.out.println(objects.poll(2, TimeUnit.SECONDS));
        System.out.println(objects.poll(2, TimeUnit.SECONDS));
//        System.out.println(objects.poll(2,TimeUnit.SECONDS));   //不抛出异常 等待两秒后结束

    }
}
